package com.gzy.mylog.controller;

import com.gzy.mylog.controller.paramer.LogPara;
import com.gzy.mylog.controller.paramer.LoginPara;
import com.gzy.mylog.core.PageList;
import com.gzy.mylog.core.R;
import com.gzy.mylog.model.Log;
import com.gzy.mylog.model.User;
import com.gzy.mylog.server.AuthServer;
import com.gzy.mylog.server.LogServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.repository.Query;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@CrossOrigin
@RestController
//@RequestMapping()
public class LogController {
    @Autowired
    LogServer server;
    @Autowired
    AuthServer authServer;

    // REST
//    浏览列表  查  GET
    @GetMapping("/log/")
    R<List<Log>> index(@AuthenticationPrincipal UserDetails userDetails){
        return new R<>(){{
            setData(server.findAll(userDetails.getUsername()));
        }};
    }

    @GetMapping("/log/page")
    R<PageList<Log>> page(
            @AuthenticationPrincipal UserDetails userDetails,
            Integer page,
            Integer size,
            @RequestParam(defaultValue = "2") Integer order
    ){
        System.out.println(String.format("page%s size%s",page.toString(),size));
        User user = authServer.getUserByUsername(userDetails.getUsername());
        return new R<>(){{
            setData(server.page(user.getId(),page,size,order));
        }};
    }


    //    添加   增  POST
    @PostMapping("/log/")
    R<Log> add(@AuthenticationPrincipal UserDetails userDetails,@Valid @RequestBody LogPara para){
        User user = authServer.getUserByUsername(userDetails.getUsername());
        Log log = server.add(user.getId(),para);

        return new R<>(){{
            setData(log);
        }};
    }
//    修改信息  改  PUT
    @PutMapping("/log/{id}")
    R<Log> update(@AuthenticationPrincipal UserDetails userDetails,@PathVariable Long id,@Valid @RequestBody LogPara para){
        User user = authServer.getUserByUsername(userDetails.getUsername());
        Log log = server.update(user.getId(),id,para);

        return new R<>(){{
            setData(log);
        }};
    }

//    删除 删  DELETE

    @DeleteMapping("/log/{id}")
    R delete(@AuthenticationPrincipal UserDetails userDetails,@PathVariable Long id){
        User user = authServer.getUserByUsername(userDetails.getUsername());
        server.delete(user.getId(),id);
        return new R<>();
    }
}
